from flask import jsonify, request
from apis.crud.sqloperate import SqlOperate
from apis.user import user

from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from apis.common.info import response_result


@user.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username == 'admin' and password == '123456':
        access_token = create_access_token(identity=username)
        data = {'token': access_token}
        result = response_result(data=data)
    elif username is None or password is None:
        msg = '用户名或密码不能为空.'
        result = response_result(401, msg)

    else:
        msg = '用户名或密码输入错误，请重新输入.'
        result = response_result(401, msg)
    return jsonify(result)


@user.route('/info')
@jwt_required
def info():
    current = get_jwt_identity()
    data = {'code': 20000,
            'message': '',
            'data': {
                'roles': [current],
                'introduction': 'I am a super administrator',
                'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
                'name': 'Super Admin'
            }
            }
    return jsonify(data)


@user.route('/logout', methods=['POST'])
@jwt_required
def logout():
    msg = '用户登出成功'
    result = response_result(message=msg)
    return jsonify(result)


@user.route('/total', methods=['POST', 'GET'])
def total():
    count = SqlOperate(tablename='war_ucenter').total()
    return jsonify({'count': count})
